package xhwl.hmo.mall.ui;

import android.Manifest;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.Constant;
import xhwl.hmo.mall.MyApp;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.event.LoginEvent;
import xhwl.hmo.mall.event.UpgradeEvent;
import xhwl.hmo.mall.http.api.GetVerifyCodeApi;
import xhwl.hmo.mall.http.api.LoginApi;
import xhwl.hmo.mall.http.api.RegJPushApi;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.http.bean.resp.LoginResp;
import xhwl.hmo.mall.http.bean.resp.ResponseError;
import xhwl.hmo.mall.http.bean.resp.SmsResp;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.BaiduLocateMgr;
import xhwl.hmo.mall.utils.JPushMgr;
import xhwl.hmo.mall.utils.NumberJudgeUtils;
import xhwl.hmo.mall.utils.PermisionUtils;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.hmo.mall.utils.UpgradeMgr;
import xhwl.hmo.mall.utils.XHLog;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


public class LoginNewActivity extends BaseActivity implements View.OnClickListener {
    private EditText etPhone,etCode;
    private TextView tvRule;
    private Button btnLogin,btnCode;
    private ImageView ivBack;
    String strSms = "获取验证码",strSms1 = "重新获取验证码",strVoice = "获取语音验证码";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_login_new);
    }

    @Override
    public void initViews() {
        ivBack= (ImageView) findViewById(R.id.ivBack);
        etCode= (EditText) findViewById(R.id.etCode);
        etPhone= (EditText) findViewById(R.id.etPhone);
        tvRule= (TextView) findViewById(R.id.tvRule);
        btnLogin= (Button) findViewById(R.id.btnLogin);
        btnCode= (Button) findViewById(R.id.btnCode);
        btnCode.setText(strSms);
        initRuleText();
        String phone = SpUtil.getString(SpUtil.MEMBER_MOBILE, "");
        etPhone.setText(phone);
        etPhone.setSelection(phone.length());
        etPhone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    boolean bool = NumberJudgeUtils.isMobileNO(etPhone.getText().toString());
                    if (bool == false) {
                        ToastUtil.showToast(mContext, "手机号格式有误，请重新输入");
                        etPhone.setText("");
                    }
                }

            }
        });
    }
    private void initRuleText() {
        SpannableString jkcn = new SpannableString("《用户协议》");
        jkcn.setSpan(new ClickableSpan() {
            /**
             * @param ds
             */
            @Override
            public void updateDrawState(TextPaint ds) {
                // TODO Auto-generated method stub
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.light_blue));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                // TODO Auto-generated method stub
                String url = "http://wx-heartorg.yk2020.com/weixin/Application/Member/View/app/info.html";
                AppUtil.startWebViewActivity(mContext, url, "用户协议");
            }
        }, 0, jkcn.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvRule.setHighlightColor(Color.TRANSPARENT);
        tvRule.append("注册登录即代表同意");
        tvRule.append(jkcn);
        // tvRule.append(jkcn);
        tvRule.setMovementMethod(LinkMovementMethod.getInstance());
    }
    @Override
    public void initListener() {
        ivBack.setOnClickListener(this);
        btnCode.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
    }
    @Override
    protected void processOper() {
        requestPermission();

    }
    @Override
    public void loadData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                if(vilidPhone()&&vilidCode()){
                    login();
                }
                break;
            case R.id.btnCode:
                if(!vilidPhone())
                    return;
                getAuthCode(etPhone.getText().toString());
                break;
            case R.id.ivBack:
                finish();
                break;
        }
    }
    private void login() {
        BaseApi api = new LoginApi(etPhone.getText().toString(), etCode.getText().toString(), AppUtil.getImei(mContext));
        HttpManager.getInstance().dealHttp(LoginNewActivity.this, api, new OnNextListener<String>() {
            @Override
            public void onNext(String str) {
                LoginResp resp = new Gson().fromJson(str, LoginResp.class);
                if (!StringUtil.isEmpty(resp.member_id)) {
                    SpUtil.putString(SpUtil.MEMBER_ID, resp.member_id);
                    SpUtil.putString(SpUtil.MEMBER_MOBILE, etPhone.getText().toString());
                    EventBus.getDefault().post(new LoginEvent(true));
                    ToastUtil.showToast(mContext, "登录成功");
                    registJPushId(resp.member_id);
                    finish();
                } else {
                    ResponseError error = new Gson().fromJson(str, ResponseError.class);
                    if (error != null && "00014".equals(error.error_code)) {
                        ToastUtil.showToast(mContext, "验证码错误");

                    } else {
                        ToastUtil.showToast(mContext, "验证失败");
                    }
                }
            }
        });

    }
    private void getAuthCode(String phone) {
        timer.start();
        String post_ip = AppUtil.getIp(mContext);
        GetVerifyCodeApi api = new GetVerifyCodeApi(phone, type, post_ip);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<SmsResp>() {
            @Override
            public void onNext(SmsResp resp) {
                if (null != resp.phone_code) {
//                    ToastUtil.showToast(mContext, "验证码已发送");
                } else {
                    cancleTimer(true);
                    ToastUtil.showToast(mContext, "验证码发送失败error_code="+resp.error_code);
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                cancleTimer(true);
            }
        });

    }

    private void cancleTimer(boolean fail) {
        timer.cancel();
        btnCode.setEnabled(true);
        btnCode.setTextColor(getResources().getColor(R.color.login_text_color));
        if(fail){
            btnCode.setText(strSms1);
        }
        else
        {
            if(type ==Constant.AUTHCODE_SMS){
                btnCode.setText(strSms);
            }else
            {
                btnCode.setText(strVoice);
            }
        }
    }
    String type = Constant.AUTHCODE_SMS;
    private CountDownTimer timer = new CountDownTimer(Constant.AUTH_TIME_ALL, Constant.AUTH_TIME_INTERAL) {

        @Override
        public void onTick(long millisUntilFinished) {
            btnCode.setEnabled(false);
            btnCode.setTextColor(getResources().getColor(R.color.main_text_color));
            btnCode.setText("("+millisUntilFinished / 1000 + "秒)");
        }

        @Override
        public void onFinish() {
            btnCode.setEnabled(true);
            btnCode.setTextColor(getResources().getColor(R.color.login_text_color));
            type=type ==Constant.AUTHCODE_SMS?Constant.AUTHCODE_VOICE:Constant.AUTHCODE_SMS;
            if(type ==Constant.AUTHCODE_SMS){
                btnCode.setText(strSms);
            }else
            {
                btnCode.setText(strVoice);
            }


        }
    };
    public boolean vilidPhone() {
        String msg = "";
        if (TextUtils.isEmpty(etPhone.getText())) {
            msg = "手机号不能为空";
        } else if (etPhone.getText().toString().length() != 11) {
            msg = "请输入11位号码";
        } else if (false == NumberJudgeUtils.isMobileNO(etPhone.getText().toString())) {
            msg = "手机号格式有误，请重新输入";
        }
        if (TextUtils.isEmpty(msg)) {
            return true;
        } else {
            ToastUtil.showToast(this, msg);
            return false;
        }
    }
    public boolean vilidCode() {
        String msg = "";
        if (TextUtils.isEmpty(etCode.getText())) {
            msg = "验证码不能为空";
        } else if (etCode.getText().toString().length() != Constant.AUTHCODE_LENGTH) {
            msg = "请输入4位验证码";
        }
        if (TextUtils.isEmpty(msg)) {
            return true;
        } else {
            ToastUtil.showToast(this, msg);
            return false;
        }
    }
    private void requestPermission() {
        new RxPermissions(this).requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA)
                .subscribe(new Action1<Permission>() {

                    @Override
                    public void call(Permission permission) {
                        if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission.name)) {
                            if (permission.granted) {
                                new UpgradeMgr().checkVersion(LoginNewActivity.this);
                            } else {
                                XHLog.e("用户拒绝开启存储");
                                PermisionUtils.dialog(LoginNewActivity.this, "读取手机存储");
                            }
                        } else if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permission.name)) {
                            if (permission.granted) {
                                BaiduLocateMgr locateMgr = new BaiduLocateMgr(LoginNewActivity.this, new BaiduLocateMgr.Callback() {
                                    @Override
                                    public void locateSuccess(double lat, double lng, String address) {
                                        MyApp.lat = lat + "";
                                        MyApp.lng = lng + "";
                                    }
                                });
                                locateMgr.startLocate();
                            } else {
                                XHLog.e("用户拒绝开启定位");
                            }
                        }
                    }
                });
    }
    public void onEvent(LoginEvent event) {
        if (event != null && event.isSuccess()) {//验证成功，关闭界面
            this.finish();
        }
    }

    public void onEvent(UpgradeEvent event) {
        if (event != null) {
            if (event.isDownloadComplete()) {
                new UpgradeMgr().checkVersion(LoginNewActivity.this);
            } else if (event.isStartDownload()) {
//                ToastUtil.showToast(this, "开始下载...");
            } else if (event.isNewest()) {
//                ToastUtil.showToast(this, "当前已是最新版本");
            } else if (event.isDownloading()) {
//                ToastUtil.showToast(this, "下载中...");
            }
        }
    }
    //需要挪到登录界面，登录成功以后调用
    private void registJPushId(final String memberId) {

        JPushMgr.getInstance().registJPushId(mContext, new JPushMgr.RegistJpushCallback() {

            @Override
            public void onResult(boolean result, final String msg) {
                // TODO Auto-generated method stub
                if (result)
                {
                    String appKey= AppUtil.getMetadata(mContext, Constant.JPUSH_APP_KEY);
                    RegJPushApi api=new RegJPushApi(memberId,msg,appKey);
                    HttpManager.getInstance().dealHttp(LoginNewActivity.this, api, new OnNextListener<HttpResp>() {
                        @Override
                        public void onNext(HttpResp resp) {
                            if (resp!=null&&resp.isOk()) {
                                XHLog.e("regist jpush id success id=" + msg);
                                JPushInterface.resumePush(mContext.getApplicationContext());
                            } else {
                                XHLog.e("regist jpush id fail id=" + msg);
                            }
                        }
                    });
                }
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != PermisionUtils.alertDialog)
            PermisionUtils.alertDialog.dismiss();
    }
}
